import { Space, Table, Pagination, Button, message, Modal, Checkbox, Form, Input } from 'antd';
import axios from 'axios';
import { useState, useEffect } from 'react';
import './App.css';
import React from 'react';
// let data = [

// ];
const Tables = () => {
  let [data, setData] = useState([]);
  let [total, setTotal] = useState(0);
  //动态设置当前页
  let [current, setCurrent] = useState(1);
  //动态设置当前页数
  let [pageSize, setPageSize] = useState(3);
  let [isModalVisible, setIsModalVisible] = useState(false);
  let [isModalVisible2, setIsModalVisible2] = useState(false);
  //函数组件更新必须通过useState,类似于类组件的this.setState
  let [rowid, setRowid] = useState(null);

  const columns = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '角色名称',
      dataIndex: 'role_name',
      key: 'role_name',
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
      key: 'mobile',
    },
    {
      title: '邮箱',
      key: 'email',
      dataIndex: 'email',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '操作',
      render: (text) => (
        <Space size="middle">
          <Button onClick={() => del(text.id)}>
            删除
          </Button>
          <Button onClick={() => update(text.id)}>
            更新
          </Button>
        </Space>

      ),
    },
  ];
  //删除
  const del = (id) => {
    console.log(id)
    axios.delete(`https://lianghj.top:8888/api/private/v1/users/${id}`, {
      headers: {
        Authorization: sessionStorage.token
      }

    }).then((res) => {
      let { meta } = res.data;
      console.log(res)
      if (meta.status === 200) {
        message.success(meta.msg)
        //删除后更新当前页和当前页数
        showTable(current, pageSize)
      } else {
        message.error(meta.msg)
      }
    })


  }


  //更新
  const update = (id) => {
    setRowid(id);
    setIsModalVisible2(true)
  }
  const handeUpdate = ({
    email, mobile
  }) => {
    axios.put(`https://lianghj.top:8888/api/private/v1/users/${rowid}`, {

      email,
      mobile
    },
      {
        headers: {
          Authorization: sessionStorage.token
        }
      }).then((res) => {
        const { meta } = res.data;
        if (meta.status === 200) {
          message.success(meta.msg)

          setIsModalVisible2(false)
          showTable(current, pageSize)
        } else {
          message.error(meta.msg)

        }

      })
  };

  /*在组件挂载或即将挂载的时候调用,会打印2次
  */
  // useEffect(()=>{
  //     axios.get('https://lianghj.top:8888/api/private/v1/users',{
  //         params:{
  //        pagesize:10,
  //        pagenum:1,
  //         },
  //         headers:{
  //          Authorization:sessionStorage.token
  //         }
  //      }).then((res)=>{
  //        let{data:{users}}=res.data;
  //        users.map((items,index)=>{
  //           return items.key=index
  //        })
  //        setData(users)
  //      })



  // },[])

  /**
   * 防抖写法
   */
  window.timer = null;
  useEffect(() => {
    clearTimeout(window.timer);
    window.timer = setTimeout(() => {
      showTable(1, 3)
    }, 0)

  }, [])


  const showTable = (pagenum, pagesize,query) => {
    axios.get('https://lianghj.top:8888/api/private/v1/users', {
      params: {
        pagenum,
        pagesize,
        query
      },
      headers: {
        Authorization: sessionStorage.token
      }
    }).then((res) => {
      let { data: { users, total } } = res.data;
      console.log(users, total)
      setTotal(total)
      users.map((items, index) => {
        return items.key = index
      })
      setData(users)
    })
  }
  const change = (page, pageSize) => {
    setCurrent(page)
    setPageSize(pageSize)
    showTable(page, pageSize)
    console.log(page, pageSize)
  }

  const add = () => {
    setIsModalVisible(true)
  }
  //新增数据
  const handeOk = ({
    username, password, email, mobile
  }) => {
    axios.post('https://lianghj.top:8888/api/private/v1/users', {
      username,
      password,
      email,
      mobile
    },
      {
        headers: {
          Authorization: sessionStorage.token
        }

      }).then((res) => {
        const { meta } = res.data;
        if (meta.status === 201) {
          message.success(meta.msg)

          setIsModalVisible(false)
          showTable(current, pageSize)
        } else {
          message.error(meta.msg)

        }

      })
  };
  //点击x号关闭模态框
  const handleCancel = () => {
    setIsModalVisible(false);
  };
  const handleCancel2 = () => {
    setIsModalVisible2(false)
  }

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };
  //查找
  const { Search } = Input;
  const onSearch = (value) =>{
    
    showTable(current, pageSize,value)


  };

  return (
    <div>
      {/* <Search placeholder="input search text" onSearch={onSearch} enterButton /> */}
      <Search
        placeholder="请输入搜索内容"
        allowClear
        enterButton="搜索"
        size="large"
        onSearch={onSearch}
        style={{width:'300px'}}
      />
      {/* <Input style={{width:'150px'}} />
            <Button type="primary" style={{marginLeft:'10px'}} onClick={()=>query}>查找</Button> */}
      <Button type="primary" style={{ float: 'right', marginBottom: '10px' }} onClick={() => add()}>新增</Button>

      <Table columns={columns} dataSource={data} pagination={false} />
      <Pagination

        current={current}
        pageSize={pageSize}
        defaultCurrent={1}
        defaultPageSize={3}

        pageSizeOptions={[1, 2, 3, 6, 10, 20, 50]}
        // hideOnSinglePage={true}
        style={{ float: 'right', marginTop: '10px' }}
        total={total}
        showSizeChanger
        showQuickJumper
        onChange={change}
        showTotal={(total) => `共计 ${total} 条`}
      />
      {
        //新增模态框
      }
      <Modal title="新增列表" visible={isModalVisible} onCancel={handleCancel} footer={null} destroyOnClose>
        <Form
          name="modalForm"
          labelCol={{
            span: 8,
          }}
          wrapperCol={{
            span: 16,
          }}
          initialValues={{
            remember: true,
          }}
          onFinish={handeOk}
          onFinishFailed={onFinishFailed}
          autoComplete="true"
        >
          <Form.Item
            label="用户名"
            name="username"
            rules={[
              {
                required: true,
                message: '请输入用户名',
              },
            ]}
          >
            <Input autoComplete="true"/>
          </Form.Item>

          <Form.Item
            label="密码"
            name="password"
            rules={[
              {
                required: true,
                message: '请输入密码',
              },
            ]}
          >
            <Input.Password autoComplete="true"/>
          </Form.Item>
          <Form.Item
            label="邮箱"
            name="email"
            rules={[
              {
                required: true,
                message: '请输入邮箱',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="手机"
            name="mobile"
            rules={[
              {
                required: true,
                message: '请输入手机号',
              },
            ]}
          >
            <Input autoComplete="true"/>
          </Form.Item>
          <Form.Item
            wrapperCol={{
              offset: 8,
              span: 16,
            }}
          >
            <Button type="primary" htmlType="submit" style={{ marginLeft: '30px', float: 'right' }}>
              新增
            </Button>
            <Button type="primary" onClick={handleCancel} style={{ float: 'right' }}>
              取消
            </Button>
          </Form.Item>

        </Form>
      </Modal>
      {
        //更新模态框
      }

      <Modal title="更新列表" visible={isModalVisible2} onCancel={handleCancel2} footer={null} destroyOnClose>
        <Form
          name="modalForm"
          labelCol={{
            span: 8,
          }}
          wrapperCol={{
            span: 16,
          }}
          initialValues={{
            remember: true,
          }}
          onFinish={handeUpdate}
          onFinishFailed={onFinishFailed}
          autoComplete="true"
        >
          <Form.Item
            label="邮箱"
            name="email"
            rules={[
              {
                required: true,
                message: '请输入邮箱',
              },
            ]}
          >
            <Input autoComplete="true"/>
          </Form.Item>
          <Form.Item
            label="手机"
            name="mobile"
            rules={[
              {
                required: true,
                message: '请输入手机号',
              },
            ]}
          >
            <Input autoComplete="true"/>
          </Form.Item>
          <Form.Item
            wrapperCol={{
              offset: 8,
              span: 16,
            }}
          >
            <Button type="primary" htmlType="submit" style={{ marginLeft: '30px', float: 'right' }}>
              更新
            </Button>
            <Button type="primary" onClick={handleCancel2} style={{ float: 'right' }}>
              取消
            </Button>
          </Form.Item>
        </Form>
      </Modal>

    </div>
  )
}


export default Tables;